package com.fawvwebanma.util;

import com.fawvwebanma.dto.TrainDto;
import com.fawvwebanma.dto.TrainPassStationDto;
import com.fawvwebanma.entity.Train;
import com.fawvwebanma.mapper.TrainMapper;
import com.fawvwebanma.mapper.TrainPassStationMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Component
public class TrainSearchUtil {
    @Autowired
    TrainPassStationMapper trainPassStationMapper;
    @Autowired
    TrainMapper trainMapper;

    public List<TrainDto> getTrainByLeaveAndArriveStations(String leaveStation, String arriveStation){
        log.info("TrainSearchUtil -->> getTrainByLeaveAndArriveStations");
        List<TrainDto> trainDtos = new ArrayList<>();
        List<Train> trains = new ArrayList<>();
        List<Train> trainsPassLeaveStation = trainPassStationMapper.getTrainByStationName(leaveStation);
        List<Train> trainsPassArriveStation = trainPassStationMapper.getTrainByStationName(arriveStation);
        for (Train train1:trainsPassLeaveStation) {
            for (Train train2:trainsPassArriveStation) {
                if(train1.getTrainNum().equals(train2.getTrainNum())){
                    trains.add(train1);
                    break;
                }
            }
        }
        for(Train train:trains){
            boolean isBreak = false;
            TrainDto trainDto = trainMapper.getTrainByTrainNum(train.getTrainNum());
            List<TrainPassStationDto> trainPassStationDtos = trainDto.getTrainPassStationDtos();
            int leaveNum = 10000;
            int arriveNum = 10000;
            for(TrainPassStationDto trainPassStationDto:trainPassStationDtos){
                if(trainPassStationDto.getStationName().contains(leaveStation)){
                    leaveNum = Integer.parseInt(trainPassStationDto.getSn());
                }
                if(trainPassStationDto.getStationName().contains(arriveStation)){
                    arriveNum = Integer.parseInt(trainPassStationDto.getSn());
                }
                if(leaveNum < arriveNum){
                    trainDtos.add(trainDto);
                    isBreak = true;
                    break;
                }else if(leaveNum > arriveNum){
                    isBreak = true;
                    break;
                }
            }
        }
//        log.info("用户查询从"+leaveStation+"到"+arriveStation+"的列车车次");
//        if(trainDtos.size() == 0){
//            log.info("没有找到相应的车次...............................");
//        }
//        log.info("找到了"+trainDtos.size()+"辆从"+leaveStation+"到"+arriveStation+"的车次");
//        for(TrainDto trainDto:trainDtos){
//            log.info(trainDto.toString());
//        }
        return trainDtos;
    }
}
